package com.scholarship.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scholarship.system.common.dto.Result;
import com.scholarship.system.entity.ResearchAbility;
import com.scholarship.system.mapper.ResearchMapper;
import com.scholarship.system.mapper.StudentMapper;
import com.scholarship.system.service.ResearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Year;
import java.time.MonthDay;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 科研能力评分服务实现类
 */
@Service
public class ResearchServiceImpl extends ServiceImpl<ResearchMapper, ResearchAbility> implements ResearchService {

    private static final Logger logger = LoggerFactory.getLogger(ResearchServiceImpl.class);

    @Autowired
    private ResearchMapper researchMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Result<List<Map<String, Object>>> getResearchScoreList(Long advisorId, String keyword, Integer year,
            String semester) {
        try {
            // 设置默认值
            if (year == null) {
                year = Year.now().getValue();
            }
            if (semester == null) {
                int month = MonthDay.now().getMonthValue();
                semester = month >= 2 && month <= 7 ? "春季" : "秋季";
            }

            // 使用Mapper查询
            List<Map<String, Object>> result = researchMapper.selectResearchScoreList(advisorId, keyword, year,
                    semester);
            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取科研评分列表异常", e);
            return Result.error("获取科研评分列表失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, Object>> getResearchScoreDetail(Long studentId, Integer year, String semester) {
        try {
            // 查询学生基本信息
            String studentSql = "SELECT s.id, s.student_id, u.name, s.college, s.major, s.grade, s.class_name " +
                    "FROM student s LEFT JOIN user u ON s.user_id = u.id WHERE s.id = ?";
            Map<String, Object> studentInfo = jdbcTemplate.queryForMap(studentSql, studentId);

            // 查询科研评分信息
            LambdaQueryWrapper<ResearchAbility> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ResearchAbility::getStudentId, studentId)
                    .eq(ResearchAbility::getYear, year)
                    .eq(ResearchAbility::getSemester, semester);
            ResearchAbility researchAbility = getOne(wrapper);

            Map<String, Object> researchInfo = new HashMap<>();
            if (researchAbility != null) {
                researchInfo.put("id", researchAbility.getId());
                researchInfo.put("student_id", researchAbility.getStudentId());
                researchInfo.put("paper_score", researchAbility.getPaperScore());
                researchInfo.put("patent_score", researchAbility.getPatentScore());
                researchInfo.put("project_score", researchAbility.getProjectScore());
                researchInfo.put("competition_score", researchAbility.getCompetitionScore());
                researchInfo.put("total_score", researchAbility.getTotalScore());
                researchInfo.put("year", researchAbility.getYear());
                researchInfo.put("semester", researchAbility.getSemester());
            } else {
                // 如果没有记录，创建默认值
                researchInfo.put("id", null);
                researchInfo.put("student_id", studentId);
                researchInfo.put("paper_score", 0);
                researchInfo.put("patent_score", 0);
                researchInfo.put("project_score", 0);
                researchInfo.put("competition_score", 0);
                researchInfo.put("total_score", 0);
                researchInfo.put("year", year);
                researchInfo.put("semester", semester);
            }

            // 查询论文记录
            String paperSql = "SELECT * FROM paper_record WHERE student_id = ? AND year = ? AND semester = ? ORDER BY publication_date DESC";
            List<Map<String, Object>> paperList = jdbcTemplate.queryForList(paperSql, studentId, year, semester);

            // 查询专利记录
            String patentSql = "SELECT * FROM patent_record WHERE student_id = ? AND year = ? AND semester = ? ORDER BY application_date DESC";
            List<Map<String, Object>> patentList = jdbcTemplate.queryForList(patentSql, studentId, year, semester);

            // 查询项目记录
            String projectSql = "SELECT * FROM project_record WHERE student_id = ? AND year = ? AND semester = ? ORDER BY start_date DESC";
            List<Map<String, Object>> projectList = jdbcTemplate.queryForList(projectSql, studentId, year, semester);

            // 查询竞赛记录
            String competitionSql = "SELECT * FROM competition_record WHERE student_id = ? AND year = ? AND semester = ? ORDER BY competition_date DESC";
            List<Map<String, Object>> competitionList = jdbcTemplate.queryForList(competitionSql, studentId, year,
                    semester);

            // 组装结果
            Map<String, Object> result = new HashMap<>();
            result.put("studentInfo", studentInfo);
            result.put("researchInfo", researchInfo);
            result.put("paperList", paperList);
            result.put("patentList", patentList);
            result.put("projectList", projectList);
            result.put("competitionList", competitionList);

            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取科研评分详情异常", e);
            return Result.error("获取科研评分详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> saveResearchScore(Map<String, Object> params) {
        try {
            logger.info("保存科研评分，参数: {}", params);

            // 参数校验
            if (params.get("studentId") == null) {
                return Result.error("学生ID不能为空");
            }
            if (params.get("year") == null) {
                return Result.error("评分年份不能为空");
            }
            if (params.get("semester") == null) {
                return Result.error("评分学期不能为空");
            }

            Long studentId;
            try {
                studentId = Long.parseLong(params.get("studentId").toString());
            } catch (NumberFormatException e) {
                logger.error("学生ID格式错误: {}", params.get("studentId"));
                return Result.error("学生ID格式错误");
            }

            Integer year;
            try {
                year = Integer.parseInt(params.get("year").toString());
            } catch (NumberFormatException e) {
                logger.error("年份格式错误: {}", params.get("year"));
                return Result.error("年份格式错误");
            }

            String semester = params.get("semester").toString();

            // 查询是否存在记录
            LambdaQueryWrapper<ResearchAbility> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ResearchAbility::getStudentId, studentId)
                    .eq(ResearchAbility::getYear, year)
                    .eq(ResearchAbility::getSemester, semester);
            ResearchAbility researchAbility = getOne(wrapper);

            if (researchAbility == null) {
                // 创建新记录
                researchAbility = new ResearchAbility();
                researchAbility.setStudentId(studentId);
                researchAbility.setYear(year);
                researchAbility.setSemester(semester);
            }

            // 设置评分信息，处理可能的空值或格式错误
            try {
                researchAbility.setPaperScore(params.get("paperScore") == null ? BigDecimal.ZERO
                        : new BigDecimal(params.get("paperScore").toString()));

                researchAbility.setPatentScore(params.get("patentScore") == null ? BigDecimal.ZERO
                        : new BigDecimal(params.get("patentScore").toString()));

                researchAbility.setProjectScore(params.get("projectScore") == null ? BigDecimal.ZERO
                        : new BigDecimal(params.get("projectScore").toString()));

                researchAbility.setCompetitionScore(params.get("competitionScore") == null ? BigDecimal.ZERO
                        : new BigDecimal(params.get("competitionScore").toString()));
            } catch (NumberFormatException e) {
                logger.error("分数格式错误: {}", e.getMessage());
                return Result.error("分数格式错误: " + e.getMessage());
            }

            // 不要手动设置总分，让数据库的生成列计算
            // 数据库中total_score是生成列: GENERATED ALWAYS AS (paper_score + patent_score +
            // project_score + competition_score) STORED

            logger.info("保存科研评分，实体: {}", researchAbility);

            // 保存或更新
            boolean success = saveOrUpdate(researchAbility);

            if (success) {
                logger.info("科研评分保存成功，ID: {}", researchAbility.getId());
                return Result.success();
            } else {
                logger.error("科研评分保存失败");
                return Result.error("保存失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("保存科研评分异常", e);
            return Result.error("保存科研评分失败: " + e.getMessage());
        }
    }
}